(function ($) {
    var imageDetails = function(response) {
        //var result = jQuery.parseJson(response);
  	  var id = $('input.drawing-board').attr('id');
  	  Drupal.canvas_fields[id].setImage(response.data);
        $('#drawCanvas').val(response.data);
    }
    
    var loadImage = function() {
  	  var nid = $('input.drawing-board').attr('id');
  	  $.get('/canvas/load/' + parseInt(nid, 10), null, imageDetails);
  	  return false;
    }
    
    var saveImage = function(id, name) {
  	  var nid = id;
  	  var imageWidth = $('#drawCanvas' + nid +'').attr('width');
  	  var imageHeight = $('#drawCanvas' + nid +'').attr('width');
  	  var imageUrl = document.getElementById("drawCanvas" + nid + "").toDataURL("image/png");
  	  var sendInfo = {
  	           nid: parseInt(nid, 10),
  	           field_name: name,
  	           display: 1,
  	           width: parseInt(imageWidth, 10),
  	           height: parseInt(imageHeight, 10),
  	           dataurl:imageUrl,
  	       };

  	       $.ajax({
  	           type: "POST",
  	           url: "/canvas/save/",
  	           dataType: "json",
  	           success: function (msg) {
  	           },

  	           data: sendInfo
  	       });
    }
    
    $.SaveLoadCanvas = function() {
    	if($('#overlay-container').length <= 0){
    		$('input.drawing-board').each(function() {
    			var id = this.id;
    			var name = this.name;
        		saveImage(id, name);
    		});
    	}
      }
    
    $.autoSaveLoadCanvas = function() {
    	if($('#overlay-container').length <= 0){
    		$('input.drawing-board').each(function() {
    			var id = this.id;
    			var name = this.name;
        		saveImage(id, name);
    		});
    	}
    	// Schedule this function to be run again in 1 sec
          setTimeout($.autoSaveLoadCanvas, 1000);
      }
})(jQuery);